package com.jblapp.icu.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.jblapp.icu.domain.AdShowInfo;

public class AdInfoParser {
	
	public static AdShowInfo getState(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		AdShowInfo info = null;
		parser.setInput(is, "utf-8");
		int type = parser.getEventType();
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("info".equals(parser.getName())) {
					info = new AdShowInfo();
					String state = parser.getAttributeValue(0);
					info.setState(state);
				} else if ("starttime".equals(parser.getName())) {
					String starttime = parser.nextText();
					info.setStarttime(starttime);
				} else if ("endtime".equals(parser.getName())) {
					String endtime = parser.nextText();
					info.setEndtime(endtime);
				}
			}
			type = parser.next();
		}
		return info;
	}

	public static AdShowInfo getAdInfo(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		AdShowInfo info = null;
		List<Map<String, String>> paths = new ArrayList<Map<String, String>>();

		parser.setInput(is, "utf-8");
		int type = parser.getEventType();
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("info".equals(parser.getName())) {
					info = new AdShowInfo();
					String state = parser.getAttributeValue(0);
					info.setState(state);
				} else if ("version".equals(parser.getName())) {
					String version = parser.nextText();
					info.setVersion(version);
				} else if ("starttime".equals(parser.getName())) {
					String starttime = parser.nextText();
					info.setStarttime(starttime);
				} else if ("endtime".equals(parser.getName())) {
					String endtime = parser.nextText();
					info.setEndtime(endtime);
				} else if ("ad".equals(parser.getName())) {
					Map<String, String> singlepath = new HashMap<String, String>();
					singlepath.put(parser.getAttributeValue(0),parser.nextText());
					paths.add(singlepath);
					info.setPath(paths);
				}
				break;
			}
			type = parser.next();
		}
		return info;
	}
}
